package org.linlinjava.litemall.admin.service;

import org.linlinjava.litemall.admin.dto.CdkeyDto;
import org.linlinjava.litemall.admin.dto.ChargeDto;
import org.linlinjava.litemall.admin.util.RedeemCodeUtils;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallCdkey;
import org.linlinjava.litemall.db.domain.LitemallCompany;
import org.linlinjava.litemall.db.domain.LitemallCompanyCharge;
import org.linlinjava.litemall.db.service.LitemallCdkeyService;
import org.linlinjava.litemall.db.service.LitemallCompanyChargeService;
import org.linlinjava.litemall.db.service.LitemallCompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.UUID;

@Service
public class AdminChargeService {
    @Autowired
    LitemallCompanyChargeService chargeService;
    @Autowired
    LitemallCdkeyService cdkeyService;
    @Autowired
    LitemallCompanyService companyService;


    private Object validate(ChargeDto chargeDto) {
        LitemallCompanyCharge charge = chargeDto.getCharge();

        if (charge.getCompanyId() == null
                || charge.getChargeMoney().compareTo(BigDecimal.ZERO) <= 0) {
            return ResponseUtil.badArgument();
        }
        if(!chargeDto.isMatchValue()){
            return ResponseUtil.fail(401, "充值金额与兑换券总金额不匹配");
        }
        return null;
    }

    @Transactional
    public Object add(ChargeDto chargeDto){
        Object error = validate(chargeDto);
        if (error != null) {
            return error;
        }
        LitemallCompanyCharge charge = chargeDto.getCharge();
        LitemallCompany company = companyService.findById(charge.getCompanyId());
        if(company == null){
            return ResponseUtil.badArgument();
        }
        charge.setCompanyName(company.getName());
        chargeService.add(charge);
        for (CdkeyDto cdkeyDto: chargeDto.getCdkeys()
             ) {
            for (int i = 0; i < cdkeyDto.getNumber(); i ++){
                LitemallCdkey cdkey = new LitemallCdkey();
                cdkey.setChargeId(charge.getId());
                cdkey.setCode(RedeemCodeUtils.createBigStrOrNumberRadom(16));
                cdkey.setCompanyId(charge.getCompanyId());
                cdkey.setFaceValue(cdkeyDto.getFaceValue());
                cdkey.setCompanyName(charge.getCompanyName());
                cdkeyService.add(cdkey);
            }
        }
        return null;
    }

}
